﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Yqd.Controllers.Filter;
using Adp.Common;
using System;
using Yqd.Core;
using System.Collections.Generic;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxAssignController : Controller
    {
        YqdContext ctx;
        DdService ddService;

        public WxAssignController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        /// <summary>
        /// 添加交办事项
        /// </summary>
        /// <returns></returns>
       [User]
        public IActionResult Add()
        {
            var TaskID = Form.GetLong("TaskID");
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            var eSuperviseID = Form.GetInt("eSuperviseID");
            var sSuperviseID = Form.GetInt("sSuperviseID");
            var datas = Form.GetString("datas").ToJArray();
            var ItemID = SuperviseID;
            var ItemType = Enm.事项类型.钉办督导;
            string headtitle = "", text = "";
            if (SuperviseID > 0)
            {
                var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                if (s != null) {
                    headtitle = "领导督导";
                    text = "督导意见  " + s.Content;
                }
            }
            if (CoordinateID > 0)
            {
                ItemID = CoordinateID;
                ItemType = Enm.事项类型.申请协调;
                var c = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == ItemID);
                if (c != null)
                {
                    headtitle = "领导协调";
                    text = "协调内容  " + c.Item;
                }
            }
            if (eSuperviseID > 0)
            {
                ItemID = eSuperviseID;
                ItemType = Enm.事项类型.精准督查;
                var s = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                if (s != null)
                {
                    headtitle = "精准督查";
                    text = "存在问题  " + s.Problem;
                }
            }
            if (sSuperviseID > 0)
            {
                ItemID = sSuperviseID;
                ItemType = Enm.事项类型.专项督查;
                var s = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                if (s != null)
                {
                    headtitle = "专项督查";
                    text = "存在问题  " + s.Problem;
                }
            }
            switch (ItemType)
            {
                case Enm.事项类型.钉办督导:
                    var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
                    if (s != null && s.Status == Enm.办理情况.已完结)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case Enm.事项类型.申请协调:
                    var r = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == CoordinateID);
                    if (r != null && r.Status == Enm.办理情况.已完结)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case Enm.事项类型.精准督查:
                    var e = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == eSuperviseID);
                    if (e != null && e.Status == Enm.办理情况.已完结)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case Enm.事项类型.专项督查:
                    var rs = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == sSuperviseID);
                    if (rs != null && rs.Status == Enm.办理情况.已完结)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
            }
            var lst = new List<Yqd_Assign>();
            var data = new List<Yqd_Cooperative>();
            foreach (var info in datas)
            {
                var model = new Yqd_Assign
                {
                    TaskID = TaskID,
                    ItemID = ItemID,
                    ItemType = ItemType,
                    Item = info["Item"].ToString(),
                    LeadUnit = info["LeadUnit"].ToString(),
                    CooperativeUnit = info["CooperativeUnit"]?.ToString() ?? "",
                    AssignLimit = DateTime.Parse(info["AssignLimit"].ToString()),
                    Instime = DateTime.Now,
                    EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                    UnitCode = WxUser.LogonInfo.UnitCode
                };
                lst.Add(model);
                if (!string.IsNullOrWhiteSpace(model.CooperativeUnit))
                {
                    var codes = model.CooperativeUnit.Split(',');
                    foreach(var c in codes)
                    {
                        data.Add(new Yqd_Cooperative
                        {
                            TaskID = TaskID,
                            Item = model.Item,
                            CooperativeUnit = c,
                            RespondTime = model.AssignLimit,
                            CooperativeResult = 0,
                            Instime = DateTime.Now,
                            EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                            UnitCode = WxUser.LogonInfo.UnitCode
                        });
                    }
                }
            }
            ctx.Yqd_Assign.AddRange(lst);
            ctx.Yqd_Cooperative.AddRange(data);
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                var state = (int)Enm.办理情况.未回复;
                var nt = DateTime.Now.Date;
                if(lst.Any(it=>it.AssignLimit< nt)) state = (int)Enm.办理情况.已滞后;
                var (tblname, keyname, IsDeal) = SuperviseService.GetTableName(ItemType);
                ctx.Database.ExecuteSql("Update Yqd_" + tblname + " set Status={1}" + (IsDeal ? ",IsDeal=1" : "") + " Where " + keyname + "ID={0}", ItemID, state);
                foreach (var m in lst)
                {
                    var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
                    if (task != null)
                    {
                        var msg = ddService.Notification(m.LeadUnit, headtitle, task.TaskName, text + "\n请本单位及时办理反馈！");
                        Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了工作通知，返回值：" + msg);
                    }
                    TaskLogService.AddLog(TaskID, "交办了" + ItemType.ToString() + "牵头单位" + ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == m.LeadUnit)?.Name);
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult Delete()
        {
            var AssignID = Form.GetInt("AssignID");
            var assign = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == AssignID);
            var sql = "delete from Yqd_Assign where AssignID={0};";
            if (assign != null)
            {
                var (tblname, keyname, IsDeal) = SuperviseService.GetTableName(assign.ItemType);
                sql += "Update Yqd_" + tblname + " set Status={2}"+(IsDeal ? ",IsDeal = 0" : "")+" Where " + keyname + "ID={1};";
            }
            var ret = ctx.Database.ExecuteSql(sql, AssignID, assign.ItemID, Enm.办理情况.待交办);
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}
